package com.mairuide.inspectionReport.utils;

import com.mairuide._frame.utils.excellistener.SpecialTemplate;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.inspectionReport.MailList;
import com.mairuide.phone.PhoneRecord;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * @Auther: zyj
 * @Date: 2019/4/9 16:44
 * @Description:
 */
public class MeiYaJsoupUtils {

    /**
     * 抓取微信转账
     * @param url
     * @throws IOException
     */
    public static List<DealFlow> weiXin(String zipPath,String url,String uid,Integer id) throws IOException {
        List<DealFlow> list = null;
        try {
            String name = url.split("#")[1].split("\\.")[1];
            zipPath = zipPath+url.split("#")[0];
//        String zipPath ="D:\\新建文件夹\\本周任务-HTML加入\\20181123004_检验报告_html\\Report\\Contents679.html";
            File in = new File(zipPath);
            Document document = Jsoup.parse(in, "UTF-8");
            Elements select = document.select("[name^="+name+"]");
            list = new ArrayList<>();
            for (Element element:select){
                String[] rivalNameAndNumber = element.text().split("/");
                String rivalName = rivalNameAndNumber[0];
                String rivalNumber = rivalNameAndNumber[1].substring(0,rivalNameAndNumber[1].indexOf("("));
                Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
                Elements td = table.select("[align=right][width=80%]");
                for (Element el:td){
                    if ("".equals(el.text()))continue;
                    DealFlow dealFlow = new DealFlow();
                    dealFlow.setAccountRival(rivalName);
                    dealFlow.setAccountRivalCard(rivalNumber);
    //                String[] split = el.text().split(" ");//，方 (wxid_e67s1khk734121) 已收钱 ￥1006.00 微信转账 2018-06-09 11:39:56
                    Element tbody = el.selectFirst("tr");
                    String[] split = tbody.text().split(" ");
                    dealFlow.setAccountBody(split[0]);
                    dealFlow.setAccountBodyCard(split[1].substring(1,split[1].length()-1));
                    Elements p = el.select("p");
                    if ("已收钱".equals(p.get(0).text())){
                        dealFlow.setSign(0);
                    }else {
                        dealFlow.setSign(1);
                    }
                    dealFlow.setAccountMoney(new BigDecimal(p.get(1).text().substring(1)));
                    dealFlow.setContentAbstract(p.get(2).text());
                    Date date = DateUtils.getDate(p.get(3).text());
                    if (date!=null)dealFlow.setTradeDate(new Timestamp(date.getTime()));
                    dealFlow.setCasemanageId(uid);
                    dealFlow.setCreateId(id);
                    dealFlow.setIsDelete(0);
                    dealFlow.setDataSources(1);
                    dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    list.add(dealFlow);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return list;
        }
    }

    /**
     * 抓取支付宝的转账
     * @param url
     * @throws IOException
     */
    public static List<DealFlow> aliplay(String zipPath,String url,String uid,Integer id) throws IOException {
        List<DealFlow> list = null;
        try {
            String name = url.split("#")[1].split("\\.")[1];
            zipPath = zipPath+url.split("#")[0];
//        String zipPath ="D:\\新建文件夹\\本周任务-HTML加入\\20181123004_检验报告_html\\Report\\Contents866.html";
            File in = new File(zipPath);
            Document document = Jsoup.parse(in, "UTF-8");
            Elements select = document.select("[name^="+name+"]");
            list = new ArrayList<>();
            String body = null;
            String bodyNumber = null;
            for (Element element:select){
                Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
                Elements selectbody = table.select("td[width=80%][align=right]");
                if (selectbody.size()>0) {
                    String[] strings = selectbody.get(0).text().split(" ");
                    body = strings[0];
                    bodyNumber = strings[1].trim().substring(1,strings[1].length()-1);
                    break;
                }
            }
            for (Element element:select){
                String[] rivalNameAndNumber = element.text().split("/");
                String rivalName = rivalNameAndNumber[0];
                String rivalNumber = rivalNameAndNumber[1].substring(0,rivalNameAndNumber[1].indexOf("("));
                Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
                Elements td = table.select("[width=80%]");
                for (Element el:td){
                    if ("".equals(el.text()))continue;
                    String align = el.attr("align");//align=right 为付钱
                    String[] split = el.text().split(" ");//牛奶不加糖 (2088122785532762) 9940.00元 转账给金鹤 转账 查看红包 红包 2018-10-12 09:16:27
                    if ("红包".equals(split[4]))continue;
                    DealFlow dealFlow = new DealFlow();
                    dealFlow.setAccountRival(rivalName);
                    dealFlow.setAccountRivalCard(rivalNumber);
                    if ("right".equals(align)){
                        dealFlow.setSign(1);
                    }else{
                        dealFlow.setSign(0);
                    }
                    if (split[2].contains("元")) {

                        dealFlow.setAccountMoney(new BigDecimal(split[2].replace("元", "")));
                        dealFlow.setContentAbstract(split[3]);
                    }else {

                        dealFlow.setAccountMoney(new BigDecimal(split[3].replace("元","")));
                        dealFlow.setContentAbstract(split[2]);
                    }
                    dealFlow.setAccountBody(body);
                    dealFlow.setAccountBodyCard(bodyNumber);
                    Date date = DateUtils.getDate(split[7] + " " + split[8]);
                    if (date!=null)dealFlow.setTradeDate(new Timestamp(date.getTime()));
                    dealFlow.setCasemanageId(uid);
                    dealFlow.setCreateId(id);
                    dealFlow.setIsDelete(0);
                    dealFlow.setDataSources(2);
                    dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    list.add(dealFlow);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return list;
        }
    }

    /**
     * 抓取银行卡号信息
     * @param url
     * @throws IOException
     */
    public static void cyberBank(String zipPath,String url) throws IOException {
        String name = url.split("#")[1];
        zipPath = zipPath+url.split("#")[0];
//        String zipPath ="D:\\新建文件夹\\本周任务-HTML加入\\20181123004_检验报告_html\\Report\\Contents875.html";
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        Elements select = document.select("[name="+name+"]");
        for (Element element:select){
            Element div = element.parent().parent().parent().parent().parent();
            Elements after = afterElements(div.parent().children(), div);
            Elements tables = after.select("table[width=800px]");
            for (Element table:tables){
                Elements trs = table.select("tr");
                trs.get(2);//size 11
                for (Element tr:trs) {
//                    System.out.println(tr.text());
                }

            }
        }
    }

    /**
     * 抓取手机通讯录
     * @param url
     * @throws IOException
     */
    public static List<MailList> phone(String zipPath,String url,String uid,Map<String ,String> map) throws IOException {
        String name = url.split("#")[1].split("\\.")[0];
        zipPath = zipPath+url.split("#")[0];
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        Elements select = document.select("[name^="+name+"]");
        List<MailList> list = new ArrayList<>();
        for (Element element:select){
            Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
            Elements trs = table.select("tr");
            for (int i=1;i<trs.size();i++){
                Elements tds = trs.get(i).select("td");
                MailList mailList = new MailList();
                mailList.setHostName(map.containsKey("hostName")?map.get("hostName"):null);
                mailList.setHostMobile(map.containsKey("hostMobile")?map.get("hostMobile"):null);
                mailList.setContactsName(tds.get(1).text());
                if ("".equals(tds.get(2).text()))continue;
                mailList.setContactsMobile(tds.get(2).text());
                String[] split = tds.get(4).text().split(" ");
                if (split.length==6) {
                    mailList.setCreateTime(new Timestamp(DateUtils.getDate(split[1] + " " + split[2]).getTime()));
                    mailList.setUpdateTime(new Timestamp(DateUtils.getDate(split[4] + " " + split[5]).getTime()));
                }
                if("否".equals(tds.get(5).text())){
                    mailList.setIsDelete(0);
                } else if ("是".equals(tds.get(5).text())){
                    mailList.setIsDelete(1);
                }
                mailList.setCasemanageId(uid);
                list.add(mailList);
            }
        }
        return list;
    }

    /**
     * 通话记录
     * @param zipPath
     * @param url
     * @param uid
     * @param map
     * @throws IOException
     */
    public static List<PhoneRecord> callRecord(String zipPath,String url,String uid,Map<String ,String> map) throws IOException {
        String name = url.split("#")[1].split("\\.")[0];
        zipPath = zipPath+url.split("#")[0];
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        Elements select = document.select("[name^="+name+"]");
        Element element = select.get(0);
        Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
        Elements trs = table.select("tr");
        List<PhoneRecord> list = new ArrayList<>();
        for (int i=1;i<trs.size();i++){
            Elements tds = trs.get(i).select("td");
            PhoneRecord pr = new PhoneRecord();
            pr.setServiceNumber(map.containsKey("hostMobile")?map.get("hostMobile"):null);
            pr.setServiceUserInformation(map.containsKey("hostName")?map.get("hostName"):null);
            pr.setPartyUserInformation(tds.get(1).text());
            String src = tds.get(2).selectFirst("img").attr("src");
            if ("src/DialogCall.png".equals(src)){
                pr.setCallType(0);
                pr.setPartyNumber(tds.get(2).text());
            } else if ("src/DialogAnswer.png".equals(src)){
                pr.setCallType(1);
                pr.setPartyNumber(tds.get(2).text());
            }else if ("src/DialogMiss.png".equals(src)){
                pr.setCallType(1);
                pr.setPartyNumber(tds.get(2).text());
            }
            pr.setStartingTime(new Timestamp(DateUtils.getDate(tds.get(3).text()).getTime()));
            String[] split = tds.get(4).text().split(":");
            int time = Integer.parseInt(split[0])*3600+Integer.parseInt(split[1])*60+Integer.parseInt(split[2]);
            pr.setTalkTime(String.valueOf(time));
            pr.setCasemanageId(uid);

            list.add(pr);


        }
        return list;

    }

    /**
     * 提取个人信息，号主姓名，手机号码
     * @param zipPath
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String ,String> basicInfo(String zipPath, String url) throws IOException {
        String name = url.split("#")[1].split("\\.")[0];
        zipPath = zipPath+url.split("#")[0];
        File in = new File(zipPath);
        Document document = Jsoup.parse(in, "UTF-8");
        Elements select = document.select("[name^="+name+"]");
        Map<String,String> map = new HashMap<>();
        Element element = select.get(0).text().contains("案件信息")?select.get(1):select.get(0);
        Element table = element.parent().parent().parent().parent().parent().nextElementSibling();
        Elements trs = table.select("tr");
        String hostName = trs.get(1).select("td").get(2).text();
        String hostMobile = trs.get(2).select("td").get(2).text();
        map.put("hostName",hostName);
        map.put("hostMobile",hostMobile);
        return map;
    }
    /**
     * 获取此元素之后的所有同级元素
     * @param elements
     * @param el
     * @return
     */
    private static Elements afterElements (Elements elements,Element el){
        Elements elementsTable = new Elements();
        boolean isRow = false;
        for(Element element :elements) {
            if (!isRow && el.text().equals(element.text())) {
                isRow = true;
                continue;
            }
            if (isRow) {
                elementsTable.add(element);
            }
        }
        return elementsTable;
    }
}
